#include <bits/stdc++.h>

#define in read()
#define fi first
#define se second
#define pb push_back
#define rep(i, x, y) for(int i = (x); i <= (y); i++) 
#define per(i, x, y) for(int i = (x); i >= (y); i--)

using namespace std;

using ll = long long;
using db = double;
using pii = pair < int , int >;
using vec = vector < int >;
using veg = vector < pii >;

int read() {
	int x = 0; bool f = 0; char ch = getchar(); while(!isdigit(ch)) f |= ch == '-', ch = getchar(); 
	while(isdigit(ch)) x = x * 10 + (ch ^ 48), ch = getchar(); return f ? -x : x;
}

const int N = 1e5 + 10;

int a[N], n, m;
ll ans, res;
int tadd[N], rdel[N], tdel[N];
ll dval[N];
int szr, szt;

int main() {
#ifndef ONLINE_JUDGE
	freopen("1.in", "r", stdin);
#endif
	n = in, m = in; rep(i, 1, n) a[i] = in;
	rep(i, 2, n) res += a[i - 1] < a[i] ? a[i] - a[i - 1] : m - a[i - 1] + a[i];
	ans = res;
	rep(i, 2, n) {
		if(a[i - 1] < a[i]) {
			tadd[a[i - 1] + 1]++; dval[a[i]] += a[i] - a[i - 1] - 1; tdel[a[i]]++;
		}
		else {
			res -= m - a[i - 1], szr++, dval[a[i]] += m - a[i - 1] + a[i] - 1; rdel[a[i]]++;
			tadd[a[i - 1] + 1]++;
		}
	}
	rep(i, 1, m) {
		ans = min(ans, res); //cerr << res << " " << szt << " " << szr << endl;
		szr -= rdel[i]; szt -= tdel[i]; szt += tadd[i];
		res -= szr; res -= szt; res += dval[i];
	} cout << ans << endl;
	return 0;
}
